import axios from 'axios'
const qs = require('qs')
const service = axios.create({
  baseURL: 'http://localhost:8000/'
})
service.interceptors.request.use(
  config => {
    config.withCredentials = false
    config.timeout = 6000
    let token = localStorage.getItem('AUTHTOKEN')
    if (token) {
      config.headers['AUTHTOKEN'] = token
    }
    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, {
          arrayFormat: 'repeat'
        })
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    if (response.data.code === 401) {
      window.location.href = '/login'
    }
    return response
  },
  error => {
    return Promise.reject(error.response.data)
  }
)
export default service
